import { Game, GameComponent } from "@sapi-game/main";
import { showWereWolfForm, WereWolfFormOptions } from "@/werewolf/func";
import { WereWolfSeerPhase } from "@/werewolf/phases/seer";
import { WereWolfPlayer, WereWolfRole } from "@/werewolf/player";
import { WereWolfNoColor } from "@/werewolf/static";

export class WereWolfChecker extends GameComponent<
    WereWolfSeerPhase,
    { itemId: string }
> {
    override onAttach(): void {
        if (!this.options) return;
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                const gamePlayer = this.state.playerManager.get(t.source);
                if (gamePlayer) {
                    this.handleCheck(gamePlayer);
                }
            },
            {
                itemId: this.options!.itemId,
                players: this.context.players,
            }
        );
    }

    formOptions: WereWolfFormOptions = {
        title: "预言家菜单",
        body: "请选择你要预言的玩家",
        getPlayers: () => this.context.players.getAll().filter((p) => !p.dead),
        onSelect: (player: WereWolfPlayer, selected: WereWolfPlayer) => {
            if (!this.isAttached) return;
            player.sendMessage(
                `[${WereWolfNoColor[selected.no - 1]}${selected.no}号§r]${
                    selected.name
                } 的身份是 ${
                    selected.role == WereWolfRole.Werewolf
                        ? "§4§l狼人"
                        : "§a§l好人"
                }`
            );
            player.clear(this.options!.itemId);
            this.state.next();
        },
    };

    handleCheck(player: WereWolfPlayer) {
        if (!player.player) return;
        if (player.role != WereWolfRole.Seer) {
            return player.sendMessage("冒充预言家，不给你预言");
        }
        showWereWolfForm(this.formOptions, player);
    }
}
